<?php

class SiteController extends MyController
{
    // {{{ *** Members ***
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    //public $layout='//layouts/column2';

    public $title="Site";
    // }}} 
    // {{{ actions
    /**
     * Declares class-based actions.
     */
    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha'=>array(
                'class'=>'CCaptchaAction',
                'backColor'=>0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page'=>array(
                'class'=>'CViewAction',
            ),
        );
    } // }}} 
    // {{{ *** Actions ***
    // {{{ actionIndex
    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex()
    {
        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/main.php'

        $cs = Yii::app()->clientScript;
        $cs->registerCoreScript('jquery');

        Yii::app()->user->setState('SelectedProjectId',null);

        $this->render(
            'index',
            array(
            )
        );

    } // }}}
    // {{{ actionCalendar
    public function actionCalendar()
    {
        $this->pageTitle = Yii::t('site','Manage Repair Orders');
        $model=new RepairOrder('search');
        $model->unsetAttributes();  // clear any default values

        if(isset($_GET['RepairOrder']))
            $model->attributes=$_GET['RepairOrder'];
        if(Yii::app()->user->checkAccess('mechanic') and !Yii::app()->user->checkAccess('manager'))
            $model->mechanicId = Yii::app()->user->id;

        $rawData = array();
        $models = $model->search()->getData();
        foreach($models as $repairOrder) {
            $obj = new CalendarEvent;
            $obj->attributes = $repairOrder->calendarAttributes;
            $rawData[] = $obj;
        }

        // Add vehicle event dates
        $vehicles = Vehicle::model()->liveUser()->findAll();
        foreach($vehicles as $vehicle) {
            if(!is_null($vehicle->nextTechCheckDate)) {
                $obj = new CalendarEvent;
                $obj->attributes = $vehicle->getCalendarAttributes('nextTechCheckDate');
                $rawData[] = $obj;
            }
            if(!is_null($vehicle->nextInspectionDate)) {
                $obj = new CalendarEvent;
                $obj->attributes = $vehicle->getCalendarAttributes('nextInspectionDate');
                $rawData[] = $obj;
            }
        }

        $dataProvider=new CArrayDataProvider($rawData, array(
            'id'=>'id',
            'sort'=>array(
                'attributes'=>array(
                     'startValue',
                ),
            ),
            'pagination'=>array(
                'pageSize'=>10,
            ),
        ));
        
        // $criteria->condition = "UNIX_TIMESTAMP(CONCAT(repairOrderDate,' ',timeStart)) BETWEEN ".mktime(0,0,0,6,6,2011)." AND ".mktime(23,59,59,6,8,2011);
        // $dataProvider = new CActiveDataProvider(RepairOrder::model()->liveUser(), array('criteria'=>$criteria));

        $this->render('calendar',array('model'=>$model, 'dataProvider'=>$dataProvider));
    } // }}} 
    // {{{ actionError
    /**
     * This is the action to handle external exceptions.
     */
    public function actionError()
    {
        if($error=Yii::app()->errorHandler->error)
        {
            if(Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    } // }}} 
    // {{{ actionContact
    /**
     * Displays the contact page
     */
    public function actionContact()
    {
        $this->layout = '//layouts/column1';
        $model=new ContactForm;
        // Do we have a logged in user?
        if(!Yii::app()->user->isGuest) {
            // Set some contact defaults
            $model->name = Yii::app()->user->firstName.' '.Yii::app()->user->lastName;
            $model->email = Yii::app()->user->email;
        }
        // $model->subject = sprintf('[%s]',Yii::app()->name);
        if(isset($_POST['ContactForm']))
        {
            $model->attributes=$_POST['ContactForm'];
            $model->subject = sprintf('[%s]',Yii::app()->name).$model->subject;
            if($model->validate())
            {
                $headers="From: {$model->email}\r\nReply-To: {$model->email}";
                $body = Yii::t('site',"This email has been sent from the {appName} contact form.\r\nLink: {link}\r\n----",array('{appName}'=>Yii::app()->name,'{link}'=>Yii::app()->request->hostInfo.Yii::app()->createUrl('/site')))."\r\n\r\n".$model->body;
                mail(Yii::app()->params['adminEmail'],$model->subject,$body,$headers);
                Yii::app()->user->setFlash('contact',Yii::t('site','Thank you for contacting us. We will respond to you as soon as possible.'));
                $this->refresh();
            }
        }
        $this->render('contact',array('model'=>$model));
    } // }}} 
    // {{{ actionRegister
    public function actionRegister()
    {
        $this->layout = '//layouts/column1';
        $model = new User;
        $model->scenario = 'register';
        if(isset($_POST['User']))
        {
            $model->attributes=$_POST['User'];
            //$model->companyId = 0;
            if($model->save()) {
                Yii::app()->user->setFlash(
                    'success',
                    '<b>'.Yii::t('site','Registration submitted').'</b><br/>'.
                    Yii::t('site','Your registration has been submitted. Upon approval, you will receive an email.')
                );
                // {{{ Send an email to the site admin
                $to      = Yii::app()->params['adminEmail'];
                $subject = '['.Yii::app()->name.'] '.Yii::t('site','New User Registration');
                $app = Yii::app()->name;
                $username = $model->username;
                $link = Yii::app()->request->hostInfo.Yii::app()->createUrl('/admin/user/update',array('id'=>$model->id));
                $message = $this->renderPartial('mailNewUserRegistration',array('app'=>$app,'link'=>$link,'username'=>$username),true);
                $headers = 'From: '.Yii::app()->params['adminEmail']."\r\n" .
                    'Reply-To: '.Yii::app()->params['adminEmail']."\r\n" .
                    'X-Mailer: PHP/' . phpversion() .
                    'MIME-Version: 1.0' . "\r\n" .
                    'Content-Type: text/plain; charset="UTF-8"' . "\r\n";

                mail($to, $subject, $message, $headers);
                // }}} End send mail
                
                $this->redirect(array('/site','registration'=>1));
            }
            $this->prepareNumericFields($model);
        }
        $this->render('register',array('model'=>$model));
    } // }}} 
    // {{{ actionLogin
    /**
     * Displays the login page
     */
    public function actionLogin()
    {
        $model=new LoginForm;

        // if it is ajax validation request
        if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if(isset($_POST['LoginForm']))
        {
            $model->attributes=$_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if($model->validate() && $model->login())
                $this->redirect(Yii::app()->user->returnUrl);
        }
        // display the login form
        $this->render('login',array('model'=>$model));
    } // }}} 
    // {{{ actionLogout
    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout()
    {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    } // }}} 
    // {{{ actionSelectLanguage
    public function actionSelectLanguage() {
        $language =$_GET['_lang'];
        Yii::app()->lc->setLanguage($language);
        $supportedLocales = $this->getSupportedLocales();
        //echo par($supportedLocales);
        Yii::app()->user->setFlash('success', '<h4>'.Yii::t('site',"User Interface Language").'</h4>'.Yii::t('site',"The language was changed to {lang}.",array('{lang}'=>$supportedLocales[$language])));
        $this->redirect(Yii::app()->request->urlReferrer);
    } // }}} 
    // {{{ actionSettings
    public function actionSettings()
    {
	$this->render('settings');
    } // }}} 
    // {{{ actionChangePassword
    public function actionChangePassword()
    {
        $model = User::model()->findByPk(Yii::app()->user->id);
        $model->scenario = 'passwordChange';
	unset($model->password);
        if(isset($_POST['User']))
	{
            $model->attributes=$_POST['User'];
            if($model->save()) {
                Yii::app()->user->setFlash( 'success', '<h4>'.Yii::t('site','Password Change').'</h4>'.Yii::t('site','Your new password has been saved.'));
                $this->redirect(array('index'));
            }
	}
	$this->render('settingsUserPassword',array('model' => $model));
    } // }}}    
    // {{{ actionForgotPassword
    public function actionForgotPassword()
    {
        unset($_SESSION['flash']);
        $cs = Yii::app()->clientScript;
        $cs->registerCoreScript('jquery');
        $model = new ForgotPasswordForm;
        if(isset($_POST['ForgotPasswordForm'])) {
            $model->attributes = $_POST['ForgotPasswordForm'];
            if($model->validate()) {
                $objUser = new User('password');
                $modelUser = User::model()->findByAttributes(array('email'=>$model->email));
                $modelUser->scenario = 'changePassword';
                $newPassword = generatePassword(6);
                $modelUser->password = $newPassword;
                $modelUser->password2 = $newPassword;
                if($modelUser->save()) {
                    Yii::log("New password for {$model->email}: $newPassword");
                    $this->setSiteFlash('success',Yii::t('site','Your password has been reset. An email has been sent to {email}.',array('{email}'=>$model->email)));
                    // {{{ Send an email to the user
                    $to      = $model->email;
                    $subject = '['.Yii::app()->name.'] '.Yii::t('site','Password has been reset');
                    $app = Yii::app()->name;
                    $link = Yii::app()->request->hostInfo.Yii::app()->createUrl('/site');
                    $message = <<< EOL
Hello,

you or someone using your email address {$model->email} has requested to reset the application password for $app.

The password has been reset to $newPassword.

You can log in here:

  $link

  
Best Regards,

--
$app
Site Admin
EOL;
                    $headers = 'From: '.Yii::app()->params['adminEmail']."\r\n" .
                        'Reply-To: '.Yii::app()->params['adminEmail']."\r\n" .
                        'X-Mailer: PHP/' . phpversion();

                    mail($to, $subject, $message, $headers);
                    // }}}
                    $this->redirect(array('index'));
                } else {
                    echo par($modelUser->errors);
                }
            }
        }
        $this->render('forgotPassword',array('model'=>$model));
    } // }}} 
    // {{{ actionChangePersonalData
    public function actionChangePersonalData()
    {
        $model = User::model()->findByPk(Yii::app()->user->id);
        $model->scenario = 'changePersonalData';
        $this->prepareDateFields($model);
        if(isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            unset($model->password, $model->password2);
            if($model->save()) {
                Yii::app()->user->setFlash('success','Your Personal Data has been changed');
                $this->redirect(array('/site/settings'));

            } else {
                $this->prepareDateFields($model);
            }
        }
        $this->render('settingsUserPersonalData',array('model'=>$model));
    } // }}} 
    // {{{ actionDisplayCompanyLogo
    /**
     * Returns the company logo image
     */
    public function actionDisplayCompanyLogo()
    {
        if(!Yii::app()->user->isGuest) {
            $model=Yii::app()->user->companySettings;
            header('Pragma: public');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Content-Transfer-Encoding: binary');
            header('Content-length: '.$model->logoFileSize);
            header('Content-Type: '.$model->logoFileType);
            //header('Content-Disposition: attachment; filename='.$model->file_name);
         
            echo $model->logoFileContent;
        }
    } // }}} 
    // }}} End Actions
}
